<?php


namespace models\Business\Tbk;


use models\Exception\Business\TbkproductException;
use Task\client;
use Yaf\Exception;
use Yaf\Registry;
use youliPhpLib\Common\RequestHelper;

class Haodanku
{
    const HAODANKU_API_KEY = 'douziyoupin';
    const HAODANKU_URL = 'http://v2.api.haodanku.com';

    /**
     * 好单库采集 定时采集
     * @param int $start
     * @param int $end
     * @param int $min_id
     * @return array
     * @throws \Exception
     */
    static public function getTbkProductFromHDKByTiming($start = 0, $end = 23, $min_id = 1) {
        $url = self::HAODANKU_URL . '/timing_items' .
            '/apikey/' . self::HAODANKU_API_KEY .
            '/start/' . (! empty($start) ? $start : 0) .
            '/end/' . (! empty($end) ? $end : 23).
            '/min_id/' . (! empty($min_id) ? $min_id : 1);
        list($header_size, $body) = RequestHelper::curlRequest($url);
        $resp = json_decode($body, true);

        $product_arr = $category_id_arr = $tbk_product_arr = [];
        $min_id = 0;
        if (isset($resp['code']) && $resp['code'] == 1 && !empty($resp['data'])) {
            $min_id = $resp['min_id'];
            foreach ($resp['data'] as $data) {
                $coupon_url = $data['couponurl'];
                parse_str($data['couponurl'], $url_arr);
                $activity_id = isset($url_arr['activityId']) ? $url_arr['activityId'] : (isset($url_arr['activity_id']) ? $url_arr['activity_id'] : '');
                if (!empty($activity_id))
                    $coupon_url = 'https://uland.taobao.com/coupon/edetail?itemId=' . $data['itemid'] . '&activityId=' . $activity_id . '&pid=' . Registry::get('config')['application']['tbk']['pid'];
                array_push($category_id_arr, $data['fqcat']);
                array_push($product_arr, [
                    'product_id' => $data['itemid'],
                    'title' => $data['itemtitle'],
                    'short_title' => $data['itemshorttitle'],
//                    'category_id_1' => $data['fqcat'],
                    'category_id' => $data['fqcat'],
                    'desc' => $data['itemdesc'],
                    'article' => ! is_null($data['guide_article']) ? $data['guide_article'] : '',
                    'link' => $coupon_url,
                    'pic' => $data['itempic'],
                    'image' => $data['itempic_copy'],
                    'video_id' => $data['videoid'],
                    'price' => $data['itemprice'],
                    'end_price' => $data['itemendprice'],
                    'coupon_price' => $data['couponmoney'],
                    'rate' => $data['tkrates'],
                    'commission' => $data['tkmoney'],
                    'today_sales' => $data['todaysale'],
                    'sales' => $data['itemsale'],
                    'coupon_receive' => $data['couponreceive2'],
                    'coupon_num' => $data['couponnum'],
                    'sales_in_2_hours' => $data['itemsale2'],
                    'coupon_start_time' => date('Y-m-d H:i:s', $data['couponstarttime']),
                    'coupon_end_time' => date('Y-m-d H:i:s', $data['couponendtime']),
                    'general_index' => $data['general_index'],
                    'activity_type' => $data['activity_type'],
                    'activity_link' => ! is_null($data['planlink']) ? $data['planlink'] : ''
                ]);
            }
        }

        return [$min_id, $product_arr];
    }

    static public function searchProduct($keyword, $page = 1, $page_size = 10) {
        $url = self::HAODANKU_URL . '/get_keyword_items' .
            '/apikey/' . self::HAODANKU_API_KEY .
            '/cid/0'.
            '/keyword/' . urlencode(urlencode($keyword)) .
            '/back/' . $page_size .
            '/min_id/' . $page;
        list($head_size, $body) = RequestHelper::curlRequest($url);
        $resp = json_decode($body, true);

        $return_data = [];
        if (isset($resp['code']) && $resp['code'] == 1 && !empty($resp['data'])) {
            // 并把返回结果发送到异步任务中，由异步任务做保存工作
            $client = new client();

            try {
                $client->connect();

                $return_data['data'] = [];
                if (count($resp['data']) == 10)
                    $resp_data[] = $resp['data'];
                else
                    $resp_data = $resp['data'];

                foreach ($resp_data as $data) {
                    $coupon_url = $data['couponurl'];
                    parse_str($data['couponurl'], $url_arr);
                    $activity_id = isset($url_arr['activityId']) ? $url_arr['activityId'] : (isset($url_arr['activity_id']) ? $url_arr['activity_id'] : '');
                    if (!empty($activity_id))
                        $coupon_url = 'https://uland.taobao.com/coupon/edetail?itemId=' . $data['itemid'] . '&activityId=' . $activity_id . '&pid=' . Registry::get('config')['application']['tbk']['pid'];
                    $product = [
                        'product_id' => $data['itemid'],
                        'title' => $data['itemtitle'],
                        'short_title' => $data['itemshorttitle'],
//                        'category_id_1' => $data['fqcat'],
                        'category_id' => $data['fqcat'],
                        'desc' => $data['itemdesc'],
                        'article' => ! is_null($data['guide_article']) ? $data['guide_article'] : '',
                        'link' => $coupon_url,// . '&pid=' . Registry::get('config')['application']['tbk']['pid'],
                        'pic' => $data['itempic'],
                        'image' => $data['itempic_copy'],
                        'video_id' => $data['videoid'],
                        'price' => $data['itemprice'],
                        'end_price' => $data['itemendprice'],
                        'coupon_price' => $data['couponmoney'],
                        'rate' => $data['tkrates'],
                        'commission' => $data['tkmoney'],
                        'today_sales' => $data['todaysale'],
                        'sales' => $data['itemsale'],
                        'coupon_receive' => $data['couponreceive2'],
                        'coupon_num' => $data['couponnum'],
                        'sales_in_2_hours' => $data['itemsale2'],
                        'coupon_start_time' => date('Y-m-d H:i:s', $data['couponstarttime']),
                        'coupon_end_time' => date('Y-m-d H:i:s', $data['couponendtime']),
                        'general_index' => $data['general_index'],
                        'activity_type' => $data['activity_type'],
                        'activity_link' => ! is_null($data['planlink']) ? $data['planlink'] : ''
                    ];

                    // 发送到异步任务
                    $client->getHDKProductIntoDb($product);
                    array_push($return_data['data'], $product);
                }

                $return_data['meta'] = [
                    'total' => 1,
                    'links' => [],
                    'total_pages' => 2,
                    'per_page' => $page_size,
                    'current_page' => $page,
                    'count' => 1
                ];
                if ($resp['min_id'] != 1) {
                    $return_data['meta']['total'] = ceil($resp['total'] / $page_size);
                    $return_data['meta']['count'] = $resp['total'];
                    $return_data['meta']['links'] = ['next_page' => $resp['min_id']];
                }

            } catch (Exception $e) {
                Registry::get('tbk_log')->err("入库异步任务失败" . $e->getMessage());
            } finally {
                $client->close();
            }
        }

        if (empty($return_data))
            throw new TbkproductException(TbkproductException::TBKPRODUCT_IS_NOT_EXISTS, TbkproductException::TBKPRODUCT_IS_NOT_EXISTS_NO);

        return $return_data;

    }
}
